﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using MethodBoundaryAspect.Fody.Attributes;

namespace Marmat.Template.WinForm
{
    /// <summary>
    ///  使代码块成为事务性代码。 
    /// </summary>
    public sealed class TransactionScopeAttribute : OnMethodBoundaryAspect
    {
        /// <summary>
        /// 初始化 Marmat.Template.WinForm.TransactionScopeAttribute 类的新实例。
        /// </summary>
        public TransactionScopeAttribute()
        {
        }

        /// <summary>
        /// 进入方法前执行。
        /// </summary>
        /// <param name="args"></param>
        public override void OnEntry(MethodExecutionArgs args)
        {
            args.MethodExecutionTag = new TransactionScope();
        }

        /// <summary>
        /// 退出方法后执行。
        /// </summary>
        /// <param name="args"></param>
        public override void OnExit(MethodExecutionArgs args)
        {
            var transactionScope = (TransactionScope)args.MethodExecutionTag;
            transactionScope.Complete();
            transactionScope.Dispose();
        }

        /// <summary>
        /// 发生异常时执行。
        /// </summary>
        /// <param name="args"></param>
        public override void OnException(MethodExecutionArgs args)
        {
            var transactionScope = (TransactionScope)args.MethodExecutionTag;
            transactionScope.Dispose();
        }
    }
}
